<?php
// +----------------------------------------------------------------------
// | CLTPHP.Pro [模型字段]
// +----------------------------------------------------------------------
// | Copyright (c) 2019-2029 https://www.cltphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( https://www.cltphp.com/detail-140.html )
// +----------------------------------------------------------------------
// | Author: chichu <1109305987@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\controller;
use app\admin\model\Model as Model;
use app\admin\model\Field as M;
use think\facade\Db;
use think\facade\Event;
use think\facade\Request;
use think\facade\View;

class Field extends Base{
    protected $field_type,$field_pattern;
    function initialize(){
        parent::initialize();
        $this->field_pattern = [
            ['name'=>'defaul','title'=>'默认'],
            ['name'=>'email','title'=>'电子邮件'],
            ['name'=>'url','title'=>'网址'],
            ['name'=>'date','title'=>'日期'],
            ['name'=>'number','title'=>'有效的数值'],
            ['name'=>'digits','title'=>'数字'],
            ['name'=>'creditcard','title'=>'信用卡号码'],
            ['name'=>'equalTo','title'=>'再次输入相同的值'],
            ['name'=>'ip4','title'=>'IP'],
            ['name'=>'mobile','title'=>'手机号码'],
            ['name'=>'zipcode','title'=>'邮编'],
            ['name'=>'qq','title'=>'QQ'],
            ['name'=>'idcard','title'=>'身份证号'],
            ['name'=>'chinese','title'=>'中文字符'],
            ['name'=>'cn_username','title'=>'中文英文数字和下划线'],
            ['name'=>'tel','title'=>'电话号码'],
            ['name'=>'english','title'=>'英文'],
            ['name'=>'en_num','title'=>'英文数字和下划线'],
        ];

        $this->field_type = [
            ['name'=>'catid','title'=>'栏目'],
            ['name'=>'title','title'=>'标题'],
            ['name'=>'text','title'=>'单行文本'],
            ['name'=>'textarea','title'=>'多行文本'],
            ['name'=>'tag','title'=>'标签'],

            ['name'=>'editor','title'=>'编辑器'],
            ['name'=>'select','title'=>'下拉列表'],
            ['name'=>'radio','title'=>'单选按钮'],
            ['name'=>'checkbox','title'=>'复选框'],

            ['name'=>'image','title'=>'单张图片'],
            ['name'=>'images','title'=>'多张图片'],
            ['name'=>'file','title'=>'文件上传'],
            ['name'=>'number','title'=>'数字'],

            ['name'=>'datetime','title'=>'日期和时间'],
            ['name'=>'posid','title'=>'推荐位'],
            ['name'=>'groupid','title'=>'会员组'],
            ['name'=>'linkage','title'=>'地址联动'],
            ['name'=>'english','title'=>'英文'],
            ['name'=>'template','title'=>'模板选择'],
        ];

    }
    public function index(){
        if(request()->isPost()){
            $mid = input('post.mid');
            $nodostatus = array('catid','title','status','createtime');
            $sysfield = array('catid','userid','username','title','thumb','keywords','description','posid','status','push_time','url','template');

            $list = M::where("modelid",$mid)->order('sort asc,id asc')->select();
            foreach ($list as $k=>$v){
                if($v['status']==1){
                    if(in_array($v['field'],$nodostatus)){
                        $list[$k]['disable']=2;
                    }else{
                        $list[$k]['disable']=0;
                    }
                }else{
                    $list[$k]['disable']=1;
                }

                if(in_array($v['field'],$sysfield)){
                    $list[$k]['delStatus']=1;
                }else{
                    $list[$k]['delStatus']=0;
                }
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list,'rel'=>1];
        }else{
            return view();
        }
    }
    //字段值修改
    public function cf(){
        $data = input('post.');
        $result = M::editSave($data);
        return $result;
    }
    //修改状态
    public function status(){
        $map['id']=input('post.id');
        //判断当前状态情况
        $status=M::where($map)->value('status');
        if($status==1){
            $data['status'] = 0;
        }else{
            $data['status'] = 1;
        }
        M::where($map)->update($data);
        return ['code'=>0,'msg'=>'编辑成功！'];
    }
    //添加字段
    public function add(){
        if(Request::isAjax()){
            config('database.fields_strict',false);
            $data = input('post.');
            $fieldName=$data['field'];
            $prefix=config('database.connections.mysql.prefix');
            $name = Model::where('id',$data['modelid'])->value('name');
            $tablename=$prefix.$name;
            $Fields=Db::getTableFields($tablename);//获取模型表所有字段名
            if(in_array($fieldName,$Fields)){
                return ['code'=>0,'msg'=>'字段名已经存在！'];
            }
            $addfieldsql =$this->get_tablesql($data,'add');
            if(isset($data['setup'])) {
                $data['setup'] = array2string($data['setup']);
            }
            $data['status'] =1;
            if(empty($data['class'])){
                $data['class'] = $data['field'];
            }
            unset($data['oldfield']);

            if (M::insert($data) !==false) {
                if(is_array($addfieldsql)){
                    foreach($addfieldsql as $sql){
                        Db::execute($sql);
                    }
                }else{
                    Db::execute($addfieldsql);
                }
                return ['code'=>0,'msg'=>'添加成功！'];
            } else {
                return ['code'=>1,'msg'=>'添加失败！'];
            }
        }else{
            $fieldType = M::where('modelid',input('mid'))->column('type');
            if(in_array('catid',$fieldType)){
                unset($this->field_type[0]);
            };
            if(in_array('title',$fieldType)){
                unset($this->field_type[1]);
            }
            $info = getTableFields('field');
            $view = [
                'type' => $this->field_type,
                'pattern'    => $this->field_pattern,
                'info'        =>$info,
                'disabled'=>['title','catid']
            ];
            return view('form',$view);
        }
    }

    //编辑字段
    public function edit(){
        if(Request::isAjax()){
            $data = Request::except(['oldfield']);
            $oldfield = input('oldfield');
            $fieldName=$data['field'];

            $name = Model::where('id',$data['modelid'])->value('name');
            $prefix=config('database.connections.mysql.prefix');
            if($this->_iset_field($prefix.$name,$fieldName) && $oldfield!=$fieldName){
                return ['code'=>1,'msg'=>'字段名重复！'];
            }

            $editfieldsql =$this->get_tablesql(input('post.'),'edit');
            if(isset($data['setup'])){
                $data['setup']=array2string($data['setup']);
            }
            if(!empty($data['unpostgroup'])){
                $data['setup'] = implode(',',$data['unpostgroup']);
            }
            if(empty($data['class'])){
                $data['class'] = $data['field'];
            }
            if (false !== M::update($data)) {
                if(is_array($editfieldsql)){
                    foreach($editfieldsql as $sql){
                        Db::execute($sql);
                    }
                }else{
                    Db::execute($editfieldsql);
                }
                return ['code'=>0,'msg'=>'修改成功！'];
            } else {
                return ['code'=>1,'msg'=>'修改失败！'];
            }
        }else{
            $id = input('param.id');
            if(empty($id)){
                return ['code'=>1,'msg'=>'缺少必要的参数！'];
            }
            $fieldInfo = M::where('id',$id)->find()->toArray();
            if($fieldInfo['setup']) $fieldInfo['setup']=string2array($fieldInfo['setup']);
            $view = [
                'info'=>$fieldInfo,
                'type'=>$this->field_type,
                'pattern'=>$this->field_pattern,
                'disabled'=>['title','catid']
            ];
            return view('form',$view);
        }
    }
    public function del() {
        $id=input('id');
        $r = M::find($id);

        M::destroy($id);
        $modelid = $r['modelid'];
        $field = $r['field'];
        $prefix=config('database.connections.mysql.prefix');
        $name = Model::where('id',$modelid)->value('name');
        $tablename=$prefix.$name;
        Db::execute("ALTER TABLE `$tablename` DROP column `$field`");//删除表字段

        return ['code'=>0,'msg'=>'删除成功！'];
    }

    //字段设置
    public function fieldType(){
        View::assign(input('param.'));
        //根据id取值
        if (input('param.id')) {
            $fieldInfo = M::where('id',input('param.id'))->find()->toArray();
            $setup = string2array($fieldInfo['setup']);
        } else {
            $fieldInfo = getTableFields('field');
            $setup = string2array($fieldInfo['setup']);
        }
        $view = [
            'fieldInfo'  => $fieldInfo,
            'setup'  => $setup,
        ];
        View::assign($view);
        return view('fieldType');
    }

    public function get_tablesql($info,$do){
        $comment = $info['name'];
        $fieldtype = $info['type'];

        if(isset($info['setup']['fieldtype'])){
            $fieldtype=$info['setup']['fieldtype'];
        }

        $modelid = $info['modelid'];
        $default=   isset($info['setup']['default'])?$info['setup']['default']:'';

        $isnull = $info['required']==0?'NULL':"NOT NULL";

        $field = $info['field'];
        $prefix = config('database.connections.mysql.prefix');
        $name = Model::where('id',$modelid)->value('name');
        $tablename=$prefix.$name;
        $maxlength = intval($info['maxlength']);

        if(isset($info['setup']['numbertype'])){
            $numbertype = $info['setup']['numbertype'];
        }else{
            $numbertype = 0;
        }

        if(isset($info['oldfield'])){
            $oldfield = $info['oldfield'];
        }

        if($do=='add'){
            $do = ' ADD ';
        }else{
            $do =  " CHANGE `".$oldfield."` ";
        }
        switch($fieldtype) {
            case 'varchar':
                if(!$maxlength){$maxlength = 255;}
                $maxlength = min($maxlength, 255);
                $sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( $maxlength ) $isnull DEFAULT '$default' COMMENT '$comment'";
                break;
            case 'tag':
                if(!$maxlength){$maxlength = 255;}
                $maxlength = min($maxlength, 255);
                $sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( $maxlength ) $isnull DEFAULT '$default' COMMENT '$comment'";
                break;

            case 'title':
                $thumb = $info['setup']['thumb'];
                $style = $info['setup']['style'];
                if(!$maxlength){$maxlength = 255;}
                $maxlength = min($maxlength, 255);
                $sql[] = "ALTER TABLE `$tablename` $do `$field` VARCHAR( $maxlength ) $isnull DEFAULT '$default' COMMENT '$comment'";


                if(!$this->_iset_field($name,'thumb')){
                    if($thumb==1) {
                        $sql[] = "ALTER TABLE `$tablename` ADD `thumb` VARCHAR( 100 ) $isnull DEFAULT '' COMMENT '缩略图'";
                    }
                }else{
                    if($thumb==0) {
                        $sql[] = "ALTER TABLE `$tablename` drop column `thumb`";
                    }
                }

                if(!$this->_iset_field($name,'title_style')){
                    if($style==1) {
                        $sql[] = "ALTER TABLE `$tablename` ADD `title_style` VARCHAR( 100 ) $isnull DEFAULT '' COMMENT '标题样式'";
                    }
                }else{
                    if($style==0) {
                        $sql[] = "ALTER TABLE `$tablename` drop column `title_style`";
                    }
                }
                break;
            case 'catid':
                $sql = "ALTER TABLE `$tablename` $do `$field` SMALLINT(5) UNSIGNED $isnull DEFAULT '0' COMMENT '$comment'";
                break;

            case 'number':
                $decimaldigits = $info['setup']['decimaldigits'];
                $default = $decimaldigits == 0 ? intval($default) : floatval($default);
                $sql = "ALTER TABLE `$tablename` $do `$field` ".($decimaldigits == 0 ? 'INT' : 'decimal( 10,'.$decimaldigits.' )')." ".($numbertype ==1 ? 'UNSIGNED' : '')."  $isnull DEFAULT '$default' COMMENT '$comment'";
                break;

            case 'tinyint':
                if(!$maxlength) $maxlength = 3;
                $maxlength = min($maxlength,3);
                $default = intval($default);
                $sql = "ALTER TABLE `$tablename` $do `$field` TINYINT( $maxlength ) ".($numbertype ==1 ? 'UNSIGNED' : '')." $isnull DEFAULT '$default' COMMENT '$comment'";
                break;


            case 'smallint':
                $default = intval($default);
                $sql = "ALTER TABLE `$tablename` $do `$field` SMALLINT ".($numbertype ==1 ? 'UNSIGNED' : '')." $isnull DEFAULT '$default' COMMENT '$comment'";
                break;

            case 'int':
                $default = intval($default);
                $sql = "ALTER TABLE `$tablename` $do `$field` INT ".($numbertype ==1 ? 'UNSIGNED' : '')." $isnull DEFAULT '$default' COMMENT '$comment'";
                break;

            case 'mediumint':
                $default = intval($default);
                $sql = "ALTER TABLE `$tablename` $do `$field` INT ".($numbertype ==1 ? 'UNSIGNED' : '')." $isnull DEFAULT '$default' COMMENT '$comment'";
                break;

            case 'mediumtext':
                $sql = "ALTER TABLE `$tablename` $do `$field` MEDIUMTEXT $isnull COMMENT '$comment'";
                break;

            case 'text':
                $sql = "ALTER TABLE `$tablename` $do `$field` TEXT $isnull COMMENT '$comment'";
                break;
            case 'posid':
                $sql = "ALTER TABLE `$tablename` $do `$field` TINYINT(2) UNSIGNED $isnull DEFAULT '0' COMMENT '$comment'";
                break;
            case 'datetime':
                $sql = "ALTER TABLE `$tablename` $do `$field` INT(11) UNSIGNED $isnull DEFAULT '0' COMMENT '$comment'";
                break;

            case 'editor':
                $sql = "ALTER TABLE `$tablename` $do `$field` TEXT $isnull COMMENT '$comment'";
                break;

            case 'image':
                $sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( 80 ) $isnull DEFAULT '' COMMENT '$comment'";
                break;

            case 'images':
                $sql = "ALTER TABLE `$tablename` $do `$field` MEDIUMTEXT $isnull COMMENT '$comment'";
                break;

            case 'file':
                $sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( 80 ) $isnull DEFAULT '' COMMENT '$comment'";
                break;

            case 'files':
                $sql = "ALTER TABLE `$tablename` $do `$field` MEDIUMTEXT $isnull COMMENT '$comment'";
                break;
            case 'template':
                $sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( 80 ) $isnull DEFAULT '' COMMENT '$comment'";
                break;
            case 'linkage':
                $sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( 80 ) $isnull DEFAULT '' COMMENT '$comment'";
                break;
        }
        return $sql;
    }

    protected function _iset_field($table,$field){
        $fields = Db::getTableFields($table);
        return array_search($field,$fields);
    }
}